package week7.day43;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author fengzihao
 * @Date 2024-05-27 19:40
 */
public class MainServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            while (true) {
                Socket accept = serverSocket.accept();
                new Thread(() -> {
                    try {
                        InputStream inputStream = accept.getInputStream();
                        byte[] bytes = new byte[1024];
                        int length = 0;
                        length = inputStream.read(bytes);
                        String msg = new String(bytes, 0, length);
                        int index = msg.indexOf("\r\n");
                        String msgLine = msg.substring(0, index);
                        String[] msgLines = msgLine.split(" ");
                        File file = new File(msgLines[1].substring(1));
                        OutputStream outputStream = accept.getOutputStream();
                        if (file.exists() && file.isFile()) {
                            FileInputStream fileInputStream = new FileInputStream(file);
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.append("HTTP/1.1 200 OK\r\n");
                            if (msgLines[1].endsWith(".txt"))
                                stringBuilder.append("Content-Type: text/html");
                            if (msgLines[1].endsWith(".png"))
                                stringBuilder.append("Content-Type: image/apng");
                            stringBuilder.append("\r\n");
                            stringBuilder.append("\r\n");
                            outputStream.write(stringBuilder.toString().getBytes("UTF-8"));
                            byte[] bytes1 = new byte[1024];
                            while (fileInputStream.read(bytes1) != -1) {
                                outputStream.write(bytes1);
                            }
                            fileInputStream.close();
                            accept.close();
                        } else {
                            outputStream.write("HTTP/1.1 404 Not Found\r\n".getBytes());
                            outputStream.write("\r\n".getBytes());
                            outputStream.write("404 Not Found".getBytes());
                            accept.close();
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
